<?php

namespace App\Http\Controllers;

use App\Models\Account;
use App\Models\Message;
use App\Models\Userinfo;
use App\Models\VerifyCode;
use Illuminate\Http\Request;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\Hash;
use Carbon\Carbon;
use Illuminate\Support\Facades\Validator;

class UserInfoController extends Controller {
    public function index() {
        return response()->json( [ 'success'=>"userinfo" ], 201 );
    }

    /**
     * 生成基于时间戳的用户昵称
     * 格式：前缀 + 压缩时间戳 + 随机后缀（保证唯一性）
     */
    function generateTimestampNickname($prefix = 'sub_') {
        // 获取当前时间戳
        $timestamp = time();
    
        // 生成4位随机数（降低同一秒内的冲突概率）
        $randSuffix = mt_rand(1000, 9999);
    
        // 将时间戳转换为更短的base36格式（可选）
        $compressedTime = base_convert($timestamp, 10, 36);
    
        // 组合最终昵称（两种方案二选一）
        return $prefix . $compressedTime . $randSuffix; // 短格式示例：用户_5la5qjvj4392
        // return $prefix . $timestamp . '_' . $randSuffix; // 原始格式示例：用户_1697801234_4392
    }

    /**
     * 返回用户信息Model
     */
    public function UserInfo($account_id){
        // 查询用户信息
        $userinfo = Userinfo::where([
            "account_id"=>$account_id
        ])->first();
        if ($userinfo == null) {
            $nickname = $this->generateTimestampNickname();
            $userinfo = Userinfo::create([
                "account_id"=>$account_id,
                "nickname"=>$nickname,
                "gender"=>0,
                "address"=>"北京市",
                "motto"=>"愛真的需要勇氣來面對六眼飛魚"
            ]);
        }
        return $userinfo;
    }

    /**
     * 获取用户信息
     * @parme 
     */
    public function getUserinfo(Request $request) {
        $account = $request->account;
        // 查询用户信息
        $userinfo = $this->UserInfo($account->id);
        
        return response()->json( ["isok"=>"1",
        'data'=>[
            'userinfo' => $userinfo
            ]
        ], 201 );
    }

    /**
     * 修改用户信息
     * @prame nickname
     */
    public function setUserInfo(Request $request){
        $request->validate( [
            'type' => 'required|string',
        ] );
        $account = $request->account;
        // 查询用户信息
        $userinfo = $this->UserInfo($account->id);

        if ($request->type == "nickname") {
            $userinfo->nickname = $request->nickname;
        }elseif ($request->type == "gender") {
            $userinfo->gender = $request->gender;
        }elseif ($request->type == "address") {
            $userinfo->address = $request->address;
        }elseif ($request->type == "motto") {
            $userinfo->motto = $request->motto;
        }
        $userinfo->save();
        return response()->json( ["isok"=>"1",
        'data'=>[
            'userinfo' => $userinfo
            ]
        ], 201 );
    }
}
?>